var websocket = require('ws').Server;
var fs = require('fs');
var crypto = require('crypto');
var ws = new websocket({
    port:10086
});
var md5='';
ws.on('connection',
function(wsocket){
    var file_path='';
    wsocket.on('message',function message(msg){
        if(typeof msg === 'string'){
            if (msg === 'end'){
                wsocket.close();
            }else if(msg==='pause'){
                console.log('暂停');
            } else if(msg==='start'){
                console.log('继续传输');
                wsocket.send('ok');
            }else if(msg==='md5'){
                  let md5Promise = check_md5(file_path);
                  md5Promise.then(md5 => {
                    wsocket.send(md5)
                  })
            }
            else{
                var message=JSON.parse(msg);
                var filename=message['file_name'];
                var path=message['path'];
                var size=message['size'];
                if (!fs.existsSync(path)){
                    fs.mkdirSync(path);
                    console.log('目录创建成功！');
                }
                file_path=path+'/'+filename;
                console.log(file_path);
                if (fs.existsSync(file_path)){
                    wsocket.send('exist');
                }else{
                    wsocket.send('ok');
                }
            }
        }else{
            fs.appendFileSync(file_path,msg,function () {
                // console.log('追加内容完成')

            });
            wsocket.send('ok')
        }
    });
    wsocket.on('close',function close() {
        console.log('连接已关闭！');
    });
    wsocket.on('error',function error(err) {
        console.log(err);
    });
    wsocket.on('open',function open() {
           console.log('连接已建立!');
    });
    console.log('连接建立');

});



function check_md5(file_path) {
  return new Promise((resolve, reject) => {
    var path = file_path;
    var md5sum = crypto.createHash('md5');
    var stream = fs.createReadStream(path);
    stream.on('data', function(chunk) {
        md5sum.update(chunk);
    });
    stream.on('end', function() {
        md5 = md5sum.digest('hex');
        resolve(md5);
        console.log('文件:'+path+',MD5签名为:'+md5);
    });
  })
}